<template>
  <!-- 复杂版的操作，暂时不要用 -->
  <el-table
    :ref="config.ref || 'basicTable'"
    v-loading="config.loading"
    :data="config.data"
    :border="config.border"
    class="basic-table"
    style="width: 100%"
    :height="config.tableHeight ||
      '100%'"
    :row-key="getRowKey"
    @filter-change="filterChange"
    @sort-change="sortChange"
    @select="handleSelect"
    @selection-change="handleSelectionChange"
  >
    <!-- <el-table-column v-if="config.multiplePageSelection" align="center">
      <template slot="header" slot-scope="scope">
        <el-input v-model="search" size="mini" placeholder="输入关键字搜索" />
      </template>
      <template slot-scope="scope">
        <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">Edit</el-button>
        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">Delete</el-button>
      </template>
    </el-table-column> -->

    <el-table-column
      v-if="config.selection"
      type="selection"
      width="48"
      align="center"
      :selectable="selectable"
      :reserve-selection="config.multiplePageSelection?config.multiplePageSelection:false"
    />

    <el-table-column
      v-for="(column, index) in config.columns"
      :key="column.id || index"
      :column-key="'table_'+index"
      :label="column.label"
      :width="column.width"
      :fixed="column.fixed"
      :sortable="column.sortable"
      :sort-method="config.sortMethod || baseSortMethod"
      :align="columnAlign(column) "
      :filters="column.filters"
      :filter-method="isShowFilter(column)?filterMethod:null"
      :show-overflow-tooltip="column.showOverflowTooltip==true?column.showOverflowTooltip:false"
      :filter-placement="column.filterPlacement?column.filterPlacement:'bottom'"
      :filter-multiple="column.filterMultiple?column.filterMultiple:false"
      :min-width="column.minWidth"
    >
      <slot slot-scope="scope">
        <!-- Image -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.Image" class="imageClass">
          <img :src="scope.row[column.prop]" :width="column.imageWidth" :height="column.imageHeight" />
          <p v-if="column.imgName" :style="{width:column.imageWidth}">
            {{ imgName(scope.row, column) }}</p>
        </div>

        <!-- Text -->
        <!-- shouldPre 换行 -->
        <div
          v-if="columnType(scope.row, column) === EnumTableColumnType.Text"
          class="textParent"
          :style="{'justify-content':columnAlign(column),'align-items':columnAlign(column) ==
            'left'?'flex-start':columnAlign(column)=='right'?'flex-end':'center'}"
        >
          <div
            v-if="column.propMethod"
            class="text"
            :style="{'text-align':columnTextAlign(column)}"
            v-html="column.propMethod(scope.row)"
          >
          </div>
          <div v-else-if="column.shouldPre" class="text" :style="{'text-align':columnTextAlign(column)}">
            <div v-for="(text, index) in renderText(scope.row, column)[0]" :key="index">
              {{ text }}
            </div>
          </div>

          <div v-else class="text" :style="{'text-align':columnTextAlign(column)}">
            <div v-for="(text, index) in renderText(scope.row, column)" :key="index">
              {{ text }}
            </div>
          </div>
        </div>

        <!-- Tag -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.Tag">
          <el-tag :type="getTagType(scope.row, column)">
            {{ getTagContent(scope.row, column) }}
          </el-tag>
        </div>

        <!-- operation -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.Operation">
          <div
            v-for="(operation, index) in column.operations"
            :key="operation.id || index"
            style="display: inline-block;"
          >
            <basic-tool-tip-button
              v-if="operation.type === EnumFilterOperationType.Nomal || operation.type === undefined"
              :basic-button-config="{...operation}"
              :data="scope.row"
            >
            </basic-tool-tip-button>

            <ModalAtButton
              v-if="operation.type === EnumFilterOperationType.ModalAtButton"
              :config="{...operation}"
              :current="scope.row"
            />

            <CheckButton
              v-if="operation.type === EnumFilterOperationType.PopoverButton"
              :check-button-config="{...operation}"
              :data="scope.row"
              :popover-key="getRowKey(scope.row)"
            >
            </CheckButton>
          </div>
        </div>

        <!-- form input -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.FormInput">
          <el-input
            v-model="scope.row[column.prop]"
            :placeholder="column.placeholder"
            @input="value => formInput(column, scope.row, value)"
          />
        </div>
        <!-- sort input -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.SortInput">
          <el-input-number
            v-model="scope.row[column.prop]"
            size="small"
            :controls="false"
            :min="column.min<=0||column.min?column.min:-Infinity"
            :max="column.max||column.max<=0?column.max:Infinity"
            :precision="column.precision?column.precision:0"
            :step="column.step?column.step:1"
            label="描述文字"
            @blur="inputBlur(column, scope.row)"
            @change="(newVal, oldValue) => inputChanges(column, scope.row, newVal, oldValue)"
          >
          </el-input-number>
        </div>

        <!-- text input -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.TextInput">
          <input-column :row-data="scope.row" :column-data="column"></input-column>
        </div>

        <!-- text copy -->
        <div v-if="columnType(scope.row, column) === EnumTableColumnType.TextCopy">
          <copy-column :row-data="scope.row" :column-data="column">
          </copy-column>
        </div>
      </slot>
    </el-table-column>
  </el-table>
</template>

<script>
  import {
    EnumTableColumnType,
    EnumFilterOperationType
  } from "../BasicList/utils/static";
  import ModalAtButton from "@/common/FilterHeader/components/ModalAtButton";
  import {
    isFunction
  } from "../BasicList/utils";
  import InputColumn from "../BasicInputColumn/InputColumn.vue";
  import CopyColumn from "../BasicCopyColumn/CopyColumn.vue";
  import BasicToolTipButton from "../BasicButton/basicToolTipButton.vue";
  import CheckButton from "@/common/FilterHeader/components/checkButton/index.vue";
  // import table from 'mock/table';

  export default {

    components: {
      ModalAtButton,
      InputColumn,
      CopyColumn,
      BasicToolTipButton,
      CheckButton
    },
    props: {
      config: {
        type: Object,
        "default": () => {}
      }
    },

    data() {
      return {
        EnumTableColumnType,
        EnumFilterOperationType,
        loading: false,
        rowIndex: -1,
        columnIndex: -1
      }
    },

    watch: {
      config: {
        handler: function(newVal, oldValue) {
          this.loading = this.config.loading;
        },
        deep: true
      }
    },

    methods: {
      columnType(row, column) {
        if (isFunction(column.type)) {
          return column.type(row, column)
        }
        return column.type
      },
      columnTextAlign(column) {
        if (column && column.columnTextAlign) {
          return column.columnTextAlign
        }
        return "left"
      },
      columnAlign(column) {
        if (column && column.columnAlign) {
          return column.columnAlign
        }
        return "center"
      },
      imgName(row, column) {
        if (isFunction(column.imgName)) {
          return column.imgName(row)
        } else if (column.imgName) {
          return row[column.imgName]
        }
        return ""
      },
      formInput(column, row, value) {
        if (isFunction(column.triggerFunc)) {
          return column.triggerFunc(row, value)
        }
        return ""
      },

      selectable(row, index) {
        if (isFunction(this.config.onSelectable)) {
          return this.config.onSelectable(row, index)
        }
        return true
      },

      inputBlur(column, row) {
        isFunction(column.onBlur) && column.onBlur(column, row)
      },
      inputChanges(column, row, newVal, oldValue) {
        isFunction(column.onChange) && column.onChange(column, row, newVal, oldValue)
      },

      clearTableSelections() {
        if (this.$refs[this.config.ref || "basicTable"]) {
          this.$refs[this.config.ref || "basicTable"].clearSelection()
        }
      },
      renderButtonContent(operation, row) {
        if (typeof operation.content === "function") {
          return operation.content(row);
        }

        return operation.content;
      },
      getRowKey(row) {
        if (this.config.rowKeyFiled) {
          return `${row[this.config.rowKeyFiled]}`
        }
      },
      isShowFilter(column) {
        if (column.filterable == true) {
          return true
        }
        return false
      },

      sortChange(params) {
        if (this.config && this.config.columns && this.config.columns.length > 0) {
          const key = params.column.columnKey;
          if (!key) {
            return
          }

          const arrayKey = key.split("_")
          if (!arrayKey || arrayKey.length < 2) {
            return
          }

          const index = +arrayKey[1]
          if (index >= 0 && index < this.config.columns.length) {
            this.config.columns.map((val) => {
              if (val.sortable != false && val.sortProp) {
                delete this.config.form[val.sortProp]
              }
            })

            const columnValue = this.config.columns[index]
            let sort = 1
            if (params.order == "descending") {
              sort = 2
            }

            this.$set(this.config.form, columnValue.sortProp, sort)
            isFunction(this.config.sortChange) && this.config.sortChange()
          }
        }
      },
      filterChange(filters) {
        if (this.config && this.config.columns && this.config.columns.length > 0) {
          const key = Object.keys(filters)[0];
          if (!key) {
            return
          }

          const arrayKey = key.split("_")
          if (!arrayKey || arrayKey.length < 2) {
            return
          }

          const index = +arrayKey[1]
          if (index >= 0 && index < this.config.columns.length) {
            const columnValue = this.config.columns[index]
            this.$set(this.config.form, columnValue.filterProp, filters[key])
            isFunction(this.config.filterChange) && this.config.filterChange()
          }
        }
      },

      filterMethod(value, row, column) {
        return true
      },
      onShowPopovers(row, operation) {
        console.log(row, operation.popoverKey)
        // row[operation.popoverKey] = true;
        // row.deletePopoverVisible = true;
        this.$forceUpdate();
        console.log("forceUpdate")
        console.log(row)
      },
      onCancelPopover(operation, row) {
        // console.log(operation.visible)
        // operation.visible = false
        // console.log(operation.visible)
        row[operation.popoverKey] = false;
        console.log("forceUpdate", operation.popoverKey)
        console.log(row)
      },
      onSubmitPopover(row, operation) {
        row[operation.popoverKey] = false;
        operation.triggerFunc(row, operation);
      },
      getAtButtonConfig(operation, row) {
        console.log(operation, row)
        return Object.assign(operation, {
          TableScope: row
        })
      },
      baseSortMethod() {},

      handleSelectionChange(selection) {
        this.config.selectionRows = selection
        isFunction(this.config.handleSelectionChange) && this.config.handleSelectionChange(selection, this.$refs[this
          .config.ref || "basicTable"]);
      },

      handleSelect(selection, row) {
        isFunction(this.config.handleSelect) && this.config.handleSelect(selection, row, this.$refs[this.config.ref ||
          "basicTable"]);
      },

      formatContent(result, column) {
        const {
          keys = []
        } = column;
        const unFormated = typeof result === "string" || typeof result === "number";
        if (unFormated) {
          return `${result}` || "-";
        }

        if (Array.isArray(result)) {
          return result.reduce((prevInfo, currentInfo) => {
            return prevInfo += `${keys.reduce((prev, current) => {
              const {
                prefix,
                suffix
              } = this.label(column, current);
              const content = `${prefix}${currentInfo[current]}${suffix}`;
              return prev = prev ? `${prev}-${content}` : `${prev}${content}`;
            }, "")}\n`;
          }, "").split("\n");
        }

        return result || "-";
      },

      label(column, key) {
        const prefix = column[`${key}Prefix`] || ""; // 文字加前缀
        const suffix = column[`${key}Suffix`] || ""; // 文字加后缀

        return {
          prefix,
          suffix
        }
      },

      renderText(row, column) {
        if (row instanceof Array) return "text"; // 获取当前条数据肯定不是数组
        if (!column || !column.prop || column.prop.length <= 0) {
          return "-"
        }

        const newRenderText = column.prop.map(key => {
          const {
            prefix,
            suffix
          } = this.label(column, key);
          const content = this.formatContent(row[key], column);

          if (Array.isArray(content)) return content;
          return `${prefix}${content}${suffix}`;
        });
        row.newRenderText = newRenderText;
        return newRenderText;
      },

      getTagType(row, column) {
        const {
          prop,
          tagTypeMap
        } = column;

        const value = row[prop];
        return tagTypeMap[value];
      },

      getTagContent(row, column) {
        const {
          prop: key
        } = column;
        const content = row[key];
        const keyMap = column[`${key}Map`]

        const {
          prefix,
          suffix
        } = this.label(column, key);

        return `${prefix}${keyMap[content]}${suffix}`;
      },

      handleClick(row, column, operation) {
        isFunction(operation.triggerFunc) && operation.triggerFunc(row, column, operation)
      }
    }

  }

</script>

<style scope lang="scss">
  ::v-deep .el-table {
    background: red;
  }

  .basic-table {
    // background: red;
    width: 100%;
  }

  //有待优化
  .textParent {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;

    .text {
      flex: 1;
      max-width: 100%;
      position: relative;
      text-align: left;
      display: inline;
    }
  }

  .imageClass {
    display: flex;
    flex-direction: column;
    text-align: center;
    align-items: center;
    justify-content: center;

    p {
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
      height: 20px;
      line-height: 20px;
      background: rgba(239, 239, 239, 1);
      border-radius: 0 0 2px 2px;
      padding-left: 2px;
      padding-right: 2px;
      font-size: 12px;
    }

    img {
      border-radius: 2px 2px 0 0;
      -webkit-border-radius: 2px 2px 0, 0;
      -moz-border-radius: 2px 2px 0, 0;
    }

  }

  // 去除横线
  .el-table {
    &::before {
      height: 0 !important;
    }
  }

  .el-table__column-filter-trigger {

    i {
      font-size: 16px;
      color: rgba(156, 168, 184, 1);
      -webkit-transform: scale(1);
      transform: scale(1);
    }

    .el-icon-arrow-down:before {
      content: "\e790";
    }
  }

  .el-table__row {
    .el-popover {
      display: none;
    }
  }

</style>
